package com.tanhua.server.service;


import com.alibaba.cloud.commons.lang.StringUtils;
import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.tanhua.autoconfig.template.OssTemplate;
import com.tanhua.commons.Constants;
import com.tanhua.dubbo.api.db.UserInfoApi;
import com.tanhua.dubbo.api.mongo.CommentApi;
import com.tanhua.dubbo.api.mongo.VideosApi;
import com.tanhua.model.db.UserInfo;
import com.tanhua.model.mongo.Comment;
import com.tanhua.model.mongo.Focus;
import com.tanhua.model.mongo.Video;
import com.tanhua.model.vo.CommentVo;
import com.tanhua.model.vo.PageResult;
import com.tanhua.model.vo.VideoVo;
import com.tanhua.server.interceptor.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
public class VideosService {
    //从调度服务器获取，一个目标存储服务器，上传
    @Autowired
    private FastFileStorageClient client;

    @Autowired
    private FdfsWebServer webServer;// 获取存储服务器的请求URL

    @Autowired
    private OssTemplate ossTemplate;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @DubboReference
    private VideosApi videosApi;

    @DubboReference
    private UserInfoApi userInfoApi;

    @DubboReference
    private CommentApi commentApi;

    @Autowired
    private MqMessageService mqMessageService;


    /**
     * 发布小视频
     *
     * @param videoThumbnail
     * @param videoFile
     */
    public void post(MultipartFile videoThumbnail, MultipartFile videoFile) {
        // 获取文件后缀名
        String filename = videoFile.getOriginalFilename();
        //不加1得到的是.mp4,我们不需要.，所以要+1
        String suffix = filename.substring(filename.lastIndexOf(".") + 1);
        try {
            String TemplateUrl = ossTemplate.upload(videoThumbnail.getOriginalFilename(), videoThumbnail.getInputStream());
            StorePath storePath = client.uploadFile(videoFile.getInputStream(), videoFile.getSize(), suffix, null);
            String videoUrl = webServer.getWebServerUrl() + storePath.getFullPath();

            Video video = new Video();
            video.setVideoUrl(videoUrl);
            video.setPicUrl(TemplateUrl);
            video.setUserId(UserHolder.getUserId());
            video.setText("黑马出品");
            videosApi.saveVideo(video);
            mqMessageService.sendLogMsg("301","video",UserHolder.getUserId().toString());
        } catch (IOException e) {
            log.error("图片保存失败");
        }
    }

    /**
     * 获取小视频列表
     *
     * @param page
     * @param pagesize
     * @return
     */
    public PageResult getVideos(Long page, Long pagesize) {
        String key = Constants.VIDEOS_RECOMMEND + UserHolder.getUserId();
        String vids = stringRedisTemplate.opsForValue().get(key);
        if (StringUtils.isNotEmpty(vids)){
            String[] vid = org.apache.commons.lang.StringUtils.split(",");
            PageResult pageResult = videosApi.getRecommend(page,pagesize,vid);
        }

        PageResult<Video> pageResult = videosApi.findVideoList(page, pagesize);
        List<Video> videoList = pageResult.getItems();
        List<VideoVo> voList = new ArrayList<>();
        for (Video video : videoList) {
            UserInfo userInfo = userInfoApi.getuserinfo(video.getUserId(), null);
            String likeKey = Constants.VIDEO_LIKE_HASHKEY + UserHolder.getUserId();
            String focusKey = Constants.FOCUS_USER_KEY + UserHolder.getUserId();
            VideoVo init = VideoVo.init(userInfo, video);
            if (stringRedisTemplate.opsForSet().isMember(likeKey, video.getId().toString())) {
                init.setHasLiked(1);
            }
            if (stringRedisTemplate.opsForSet().isMember(focusKey, video.getUserId().toString())) {
                init.setHasFocus(1);
            }
            voList.add(init);
        }
        return new PageResult(pageResult.getPage(), pageResult.getPagesize(), pageResult.getCounts(), voList);
    }

    /**
     * 视频用户关注
     *
     * @param uid
     */
    public void userFocus(Long uid) {
        Focus focus = new Focus();
        focus.setFocus(true);
        focus.setFocusUserId(uid);
        focus.setUserId(UserHolder.getUserId());
        videosApi.focusUser(focus, UserHolder.getUserId());
        String key = Constants.FOCUS_USER_KEY + UserHolder.getUserId();
        stringRedisTemplate.opsForSet().add(key, uid.toString());
    }

    /**
     * 视频用户关注 - 取消
     *
     * @param uid
     */
    public void userUnFocus(Long uid) {
        String key = Constants.FOCUS_USER_KEY + UserHolder.getUserId();
        stringRedisTemplate.opsForSet().remove(key, uid.toString());
        videosApi.userUnFocus(uid, UserHolder.getUserId());
    }

    /**
     * 视频点赞
     *
     * @param id
     */
    public void likeVideo(String id) {
        videosApi.likeVideo(id, UserHolder.getUserId());
        String key = Constants.VIDEO_LIKE_HASHKEY + UserHolder.getUserId();
        stringRedisTemplate.opsForSet().add(key, id);
        mqMessageService.sendLogMsg("0302","likevideo",id);
    }

    /**
     * 视频点赞 - 取消
     *
     * @param id
     * @return
     */
    public void disLike(String id) {
        videosApi.disLike(id, UserHolder.getUserId());
        String key = Constants.VIDEO_LIKE_HASHKEY + UserHolder.getUserId();
        stringRedisTemplate.opsForSet().remove(key, id);
        mqMessageService.sendLogMsg("0303","dislikevideo",id);
    }

    public PageResult getComments(ObjectId id, PageResult result) {
        PageResult<Comment> comment = commentApi.getComment(result, id);
        List<Comment> items = comment.getItems();
        List<CommentVo> voList = new ArrayList<>();
        for (Comment item : items) {
            UserInfo userInfo = userInfoApi.getuserinfo(item.getUserId(), null);
            CommentVo init = CommentVo.init(userInfo, item);
            voList.add(init);
        }
        return new PageResult(comment.getPage(),comment.getPagesize(),comment.getCounts(),voList);
    }
}
